package com.hsy.linemoney.modules.account;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.deparse.dpframe.tools.utils.DPGsonUtil;
import com.deparse.dpframe.tools.utils.DPLogUtil;
import com.hsy.linemoney.R;
import com.hsy.linemoney.apiservice.AccountService;
import com.hsy.linemoney.apiservice.BankService;
import com.hsy.linemoney.apiservice.Callback;
import com.hsy.linemoney.apiservice.CountryService;
import com.hsy.linemoney.apiservice.PaymentService;
import com.hsy.linemoney.modules.common.CommonBaseActivityWithSimpleActionBar;
import com.hsy.linemoney.modules.common.EditTextExt;
import com.hsy.linemoney.utils.CommonUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class CreateReceiveAccountActivity extends CommonBaseActivityWithSimpleActionBar implements View.OnClickListener {

    protected EditText firstName, lastName;
    protected EditText tel;
    protected EditText email;
    protected TextView selectCountrySpinner;
    protected EditText zipcode;
    protected TextView selectBankNameSpinner;
    protected EditText bankAccount;
    protected TextView selectReceiveTypeSpinner;
    protected EditTextExt state;
    protected EditTextExt address;
    private View bankAccountInfoPanel;
    private int selectedCountryWitch = -1;
    private int selectedBankWhitch = -1;
    private int selectedReceiveTypeWhitch = -1;
    private CountryService.CountryListResult mCountryListResult;
    private PaymentService.PaymentTypeListResult mPaymentTypeListResult;
    private BankService.BankListResult mBankListResult;
    private EditText accountName;
    private EditText city;

    @Override
    public int getRightbuttonTextResId() {
        return R.string.txt_save;
    }

    @Override
    public boolean onActionBarRightButtonClicked(ImageButton rightButton) {
        if (checkThrought()) {
            DPLogUtil.d("onActionBarRightButtonClicked checkThrought true");
            showProgressDialog(this);
            AccountService service = new AccountService();
            CreateAccountAndHolderParamsModel p = new CreateAccountAndHolderParamsModel();
            p.setFirstName(firstName.getText().toString());
            p.setLastName(lastName.getText().toString());
            p.setPhone(tel.getText().toString());
            p.setEmail(email.getText().toString());
            p.setCountryCd(mCountryListResult.getCountryList().get(selectedCountryWitch).getA2());
            p.setCity(city.getText().toString());
            p.setState(state.getText().toString());
            p.setAddressLine1(address.getText().toString());
            p.setZipCode(zipcode.getText().toString());
            p.setPaymentTypeCd(mPaymentTypeListResult.getValue().get(selectedReceiveTypeWhitch).getPaymentTypeCd());
            p.setAccountName(accountName.getText().toString());

            final String selectedReceiveType = mPaymentTypeListResult.getValue().get(selectedReceiveTypeWhitch).getPaymentTypeCd();
            if ("bank".equalsIgnoreCase(selectedReceiveType)) {
                p.setBankCd(mBankListResult.getValue().get(selectedBankWhitch).getBankCd());
                p.setBankAccount(bankAccount.getText().toString());
            }/* else if ("card".equalsIgnoreCase(selectedReceiveType)) {

            } else if ("zhifubao".equalsIgnoreCase(selectedReceiveType)) {

            } else if ("paypal".equalsIgnoreCase(selectedReceiveType)) {

            }*/

            p.setAccountTypeCd(getActivityStartExtra()[0]);
//            p.setPaymentTypeCd(getActivityStartExtra()[1]);
            p.setCurrencyCd(getActivityStartExtra()[2]);
            try {
                JSONObject params = new JSONObject(DPGsonUtil.toJson(p));
                DPLogUtil.d("onActionBarRightButtonClicked params=" + params.toString());
                service.createAccountAndHolder(params, new Callback<JSONArray>() {
                    @Override
                    public void onSuccess(int what, JSONArray result) {
                        AccountService service = new AccountService();
                        service.getAccounts(new Callback<AccountService.AccountListResult>() {
                            @Override
                            public void onSuccess(int what, AccountService.AccountListResult result) {
                                DPLogUtil.d("onSuccess result=" + DPGsonUtil.toJson(result));
                                finish();
                                hideProgressDialog();
                            }

                            @Override
                            public void onError(int what, int type, String msg, Exception e) {
                                DPLogUtil.d("onError msg=" + msg);
                                finish();
                                hideProgressDialog();
                            }
                        }, true);
                    }

                    @Override
                    public void onError(int what, int type, String msg, Exception e) {
                        showToast(R.string.txt_account_add_failure);
                        DPLogUtil.d("onError msg=" + msg);
                        e.printStackTrace();
                        hideProgressDialog();
                    }
                });
            } catch (JSONException e) {
                showToast(R.string.txt_account_add_failure);
                e.printStackTrace();
                DPLogUtil.d("onError msg=" + e.getLocalizedMessage());
                hideProgressDialog();
            }
        } else {
            DPLogUtil.d("onActionBarRightButtonClicked checkThrought false");
        }
        return true;
    }

    private boolean checkThrought() {
        boolean b = notEmpty(firstName, R.string.txt_first_name)
                && notEmpty(lastName, R.string.txt_first_name)
                && notEmpty(tel, R.string.txt_tel)
                && notEmpty(email, R.string.txt_email)
                && isSelected(selectedCountryWitch, R.string.txt_country)
                && notEmpty(city, R.string.txt_city)
                && notEmpty(state, R.string.txt_state)
                && notEmpty(address, R.string.txt_address)
                && notEmpty(zipcode, R.string.txt_zipcode)
                && isSelected(selectedReceiveTypeWhitch, R.string.txt_receive_type);
        DPLogUtil.d("b=" + b + ", " + mPaymentTypeListResult.getValue().get(selectedReceiveTypeWhitch).getPaymentTypeCd());
        if ("bank".equalsIgnoreCase(mPaymentTypeListResult.getValue().get(selectedReceiveTypeWhitch).getPaymentTypeCd())) {
            if (!b) {
                return false;
            }
            b = b && isSelected(selectedBankWhitch, R.string.txt_bank_name)
                    && notEmpty(bankAccount, R.string.txt_bank_account);
            return b;
        } else {
            return b;
        }
    }

    private boolean isSelected(int spinnerWhich, int msg) {
        if (spinnerWhich < 0) {
            showToast(getString(R.string.txt_xx_not_selected, getString(msg)));
            return false;
        }
        return true;
    }

    private boolean notEmpty(EditText editText, int msg) {
        if (TextUtils.isEmpty(editText.getText())) {
            showToast(getString(R.string.txt_xx_not_filled, getString(msg)));
            return false;
        }
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(R.string.txt_add_receiver);
        super.setContentView(R.layout.activity_add_receve_account);
        initView();
        setRightButtonTextColor(android.R.color.white);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.select_country_spinner) {
            CountryService countryService = new CountryService();
            countryService.getCountries(new Callback<CountryService.CountryListResult>() {
                @Override
                public void onSuccess(int what, final CountryService.CountryListResult result) {
                    showListDialog(result.getCountryNamesArray(), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            selectedCountryWitch = which;
                            selectCountrySpinner.setText(result.getCountryNamesArray()[which]);
                        }
                    });
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {

                }
            });
        } else if (view.getId() == R.id.select_receive_type_spinner) {
            PaymentService paymentService = new PaymentService();
            paymentService.getPaymentType(new Callback<PaymentService.PaymentTypeListResult>() {
                @Override
                public void onSuccess(int what, final PaymentService.PaymentTypeListResult result) {
                    showListDialog(result.getPaymentNameArray(), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            selectedReceiveTypeWhitch = which;
                            selectReceiveTypeSpinner.setText(result.getPaymentNameArray()[which]);

                            if ("bank".equalsIgnoreCase(result.getValue().get(which).getPaymentTypeCd())) {
                                bankAccountInfoPanel.setVisibility(View.VISIBLE);
                            } else {
                                bankAccountInfoPanel.setVisibility(View.GONE);
                            }
                        }
                    });
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {

                }
            });
        } else if (view.getId() == R.id.select_bank_name_spinner) {
            BankService bankService = new BankService();
            bankService.getBankList(new Callback<BankService.BankListResult>() {
                @Override
                public void onSuccess(int what, final BankService.BankListResult result) {
                    showListDialog(result.getBankNameArray(), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            selectedBankWhitch = which;
                            selectBankNameSpinner.setText(result.getBankNameArray()[which]);
                        }
                    });
                }

                @Override
                public void onError(int what, int type, String msg, Exception e) {

                }
            });
        }
    }

    private void initView() {
        firstName = (EditText) findViewById(R.id.first_name);
        lastName = (EditText) findViewById(R.id.last_name);
        tel = (EditText) findViewById(R.id.tel);
        email = (EditText) findViewById(R.id.email);
        selectCountrySpinner = (TextView) findViewById(R.id.select_country_spinner);
        selectCountrySpinner.setOnClickListener(CreateReceiveAccountActivity.this);
        selectReceiveTypeSpinner = (TextView) findViewById(R.id.select_receive_type_spinner);
        selectReceiveTypeSpinner.setOnClickListener(CreateReceiveAccountActivity.this);
        zipcode = (EditText) findViewById(R.id.zipcode);
        selectBankNameSpinner = (TextView) findViewById(R.id.select_bank_name_spinner);
        selectBankNameSpinner.setOnClickListener(CreateReceiveAccountActivity.this);
        bankAccount = (EditText) findViewById(R.id.bank_account);
        accountName = (EditText) findViewById(R.id.account_name);
        city = (EditText) findViewById(R.id.city);
        state = (EditTextExt) findViewById(R.id.state);
        address = (EditTextExt) findViewById(R.id.address);

        bankAccountInfoPanel = findViewById(R.id.bank_account_info_panel);

        new CountryService().getCountries(new Callback<CountryService.CountryListResult>() {
            @Override
            public void onSuccess(int what, CountryService.CountryListResult result) {
                CreateReceiveAccountActivity.this.mCountryListResult = result;
            }

            @Override
            public void onError(int what, int type, String msg, Exception e) {

            }
        });

        new PaymentService().getPaymentType(new Callback<PaymentService.PaymentTypeListResult>() {
            @Override
            public void onSuccess(int what, PaymentService.PaymentTypeListResult result) {
                CreateReceiveAccountActivity.this.mPaymentTypeListResult = result;
            }

            @Override
            public void onError(int what, int type, String msg, Exception e) {

            }
        });

        new BankService().getBankList(new Callback<BankService.BankListResult>() {
            @Override
            public void onSuccess(int what, BankService.BankListResult result) {
                CreateReceiveAccountActivity.this.mBankListResult = result;
            }

            @Override
            public void onError(int what, int type, String msg, Exception e) {

            }
        });
    }

    private void showListDialog(String[] items, DialogInterface.OnClickListener listener) {
        new AlertDialog.Builder(this).setItems(items, listener).show();
    }
}
